package utils

import (
	"errors"
	"net/url"

	"github.com/smartwalle/alipay/v3"

	"2106A-zg6/baidu/srv/nacos_init"
)

var (
	n      nacos_init.NacosContent
	client *alipay.Client
)

func AliPayInit() {

	aliCfg := n.AliPay
	client, _ = alipay.New(aliCfg.AppId, aliCfg.PrivateKey, false)
	client.LoadAliPayPublicKey(aliCfg.AliPublicKey)
}

func AliPay(subject string, outTradeNo string, totalAmount string) (string, error) {

	ali := alipay.TradePagePay{
		Trade: alipay.Trade{
			NotifyURL:   "http://isku69.natappfree.cc/notify",
			ReturnURL:   "/return",
			Subject:     subject,
			OutTradeNo:  outTradeNo,
			TotalAmount: totalAmount,
			ProductCode: "FAST_INSTANT_TRADE_PAY",
		},
	}

	url, err := client.TradePagePay(ali)
	if err != nil {
		return "", errors.New("生成支付地址失败")
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	return url.String(), nil
}

func CheckNotify(values url.Values) (*alipay.Notification, error) {
	return client.DecodeNotification(values)
}
